import React, { Component } from 'react';
import { connect } from 'dva';
import { Modal, Form, Input, InputNumber, Table, TreeSelect, Popconfirm, Select, Button, Row, Col, } from 'antd';
const TreeNode = TreeSelect.TreeNode;
const FormItem = Form.Item;
const Option = Select.Option;
var selectList = [], selectedRows = [];
function addSelectlist(obj) {
  var ind = selectList.indexOf(obj.id_);
  if (ind == -1) {
    selectedRows.push(obj);
    selectList.push(obj.id_);
  }
}
function delSelectlist(obj) {
  var ind = selectList.indexOf(obj.id_);
  if (ind !== -1) {
    selectList.splice(ind, 1);
    selectedRows.splice(ind, 1);
  }
}
function retSelectlist(list) {
  selectList = [];
  selectedRows = [];
  for (var i = 0; i < list.length; i++) {
    selectedRows.push(list[i]);
    selectList.push(list[i].id_);
  }
}

class SecondResourceGroupModal extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      selectList: [],
    };
  }

  componentWillReceiveProps(props) {
    if (!this.props.visible && props.visible) {
      retSelectlist(props.detailList);
      this.setState({ selectList });
    }
  }

  // 将选中的数据放在state里
  onSelectChange = (selectedRowKeys, selectedRows) => {
    selectList.push(selectedRowKeys);
    this.setState({ selectedRows });
  };
  onSelect = (record, selected, selectedRows) => {
    if (selected) {
      addSelectlist(record);
    } else {
      delSelectlist(record);
    }
    this.setState({ selectList });
  };

  onSelectAll = (selected, selectedRows, changeRows) => {
    if (selected) {
      for (var i = 0; i < changeRows.length; i++) {
        addSelectlist(changeRows[i]);
      }
    } else {
      for (var i = 0; i < changeRows.length; i++) {
        delSelectlist(changeRows[i]);
      }
    }
    this.setState({ selectList });
  };
  onSelectInvert = (selectedRows, dsd3, dsaf3) => {
    var i = 0, k = 0;
    for (i = 0; i < this.props.assetList.length; i++) {
      var obj = false;
      for (k = 0; k < selectedRows.length; k++) {
        if (this.props.assetList[i].id_ == selectedRows[k]) {
          obj = true;
        }
      }
      if (obj) {
        addSelectlist(this.props.assetList[i]);
      } else {
        delSelectlist(this.props.assetList[i]);
      }
    }
    this.setState({ selectList });
  };

  handleClearForm = () => {
    this.props.form.resetFields();
  }

  render() {
    const { children, assetType, dispatch, title, detailList, roomList, assetList, assetBrandList, item, assetCurrent, assetCurrentSize, assetTotal } = this.props;
    const { getFieldDecorator, getFieldsValue } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
    };
    const paginationDetail = {
      current: assetCurrent,
      pageSize: assetCurrentSize,
      total: assetTotal,
      showSizeChanger: true,
      showTotal: (total => '共' + assetTotal + '条'),
      onShowSizeChange(current, size) {
        dispatch({
          type: 'resourceGroup/querAssetListByParam',
          payload: { ...getFieldsValue(), ...{ 'pageNum': current, 'pageSize': size } },
        });
      },
      onChange(current) {
        dispatch({
          type: 'resourceGroup/querAssetListByParam',
          payload: { ...getFieldsValue(), ...{ 'pageNum': current, 'pageSize': assetCurrentSize } },
        });
      },
    };

    const loop = data => data.map((item) => {
      if (item.assetType && item.assetType.length) {
        return <TreeNode key={item.id_ + ''} title={item.name} disabled value={item.id_ + ''}>{loop(item.assetType)}</TreeNode>;
      }
      return <TreeNode key={item.id_ + ''} title={item.name} value={item.id_ + ''} />;
    });

    const getBrand = data => data.map((item) => {
      return <Option key={item.id_ + ''}>{item.name}</Option>
    })

    //根据条件筛选设备
    const searchHandle = () => {
      this.props.form.validateFields((err, values) => {
        if (!err) {
          dispatch({
            type: 'resourceGroup/querAssetListByParam',
            payload: values,
          });
        }
      });
    }

    // 点击保存将state里的选中的值放到回显给父级页面上
    const okHandler = () => {
      var arr = [];
      for (var i = 0; i < selectedRows.length; i++) {
        arr.push(selectedRows[i]);
      }
      dispatch({
        type: 'resourceGroup/changeDetailList',
        payload: { detailList: arr, assetCurrent: 1, assetTotal: 0, assetList: [] },
      });
    };

    const rowSelection = {
      selections: true,
      selectedRowKeys: this.state.selectList,
      onSelect: this.onSelect.bind(this),
      onSelectAll: this.onSelectAll.bind(this),
      onSelectInvert: this.onSelectInvert.bind(this),
    };

    const columns = [{
      title: '资产编号',
      fixed: 'left',
      dataIndex: 'assetNo',
      key: 'assetNo',
      width: 100
    }, {
      title: '资产分类',
      dataIndex: 'typeName',
      key: 'typeName',
      width: 100
    }, {
      title: '设备名称',
      dataIndex: 'assetName',
      key: 'assetName',
      width: 100
    }, {
      title: '品牌',
      dataIndex: 'brandName',
      key: 'brandName',
      width: 100,
    }, {
      title: '设备型号',
      dataIndex: 'modelName',
      key: 'modelName',
      width: 100,
    }, {
      title: '设备序列号',
      dataIndex: 'serialNo',
      key: 'serialNo',
      width: 100,
    }, {
      title: 'RFID编码',
      dataIndex: 'rfidNo',
      key: 'rfidNo',
      width: 100,
    }, {
      title: '状态',
      dataIndex: 'statusName',
      key: 'statusName',
      width: 70
    }, {
      title: '所在机房',
      dataIndex: 'roomName',
      key: 'roomName',
      width: 100,
    }, {
      title: '所在机柜',
      dataIndex: 'rackName',
      key: 'rackName',
      width: 100,
    }, {
      title: '起始U位',
      dataIndex: 'startU',
      key: 'startU',
      width: 60,
    }, {
      title: '购置时间',
      dataIndex: 'buyTime',
      key: 'buyTime',
      width: 120,
    }, {
      title: '维保结束日期',
      dataIndex: 'expirationTime',
      key: 'expirationTime',
      width: 120,
    }];

    return (
      <span>
        <Modal
          maskClosable={this.props.maskClosable}
          confirmLoading={this.props.confirmLoading}
          title={this.props.title}
          width={1000}
          visible={this.props.visible}
          onOk={okHandler.bind(this)}
          onCancel={this.props.onCancel}
          key={this.props.newKey}
        >
          <div style={{ backgroundColor: '#fff' }}>
            <div style={{ minWidth: '100%', }}>
              <div style={{ width: '100%', backgroundColor: '#fff', paddingLeft: '20px' }}>
                <Form layout="inline" style={{ marginTop: '-16px' }}>
                  <FormItem style={{ marginBottom: '0px' }}>
                    {getFieldDecorator('searchStatusType', { initialValue: 4 })(
                      <Input type="hidden" />
                    )}
                  </FormItem>
                  <Row>
                    <Col span={7}>
                      <FormItem
                        label="资产分类"
                        hasFeedback
                      >
                        {
                          getFieldDecorator('typeId')(
                            <TreeSelect
                              showSearch
                              treeNodeFilterProp="title"
                              style={{ width: '180px' }}
                              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                              placeholder="请选择资产分类"
                              allowClear
                              treeDefaultExpandAll
                            >
                              {assetType.assetType && loop(assetType.assetType)}
                            </TreeSelect>
                          )
                        }
                      </FormItem>
                    </Col>
                    <Col span={6}>
                      <FormItem
                        label="品牌"
                        hasFeedback
                      >
                        {getFieldDecorator('brandId')(
                          <Select
                            showSearch
                            allowClear
                            style={{ width: '180px' }}
                            placeholder="请选择品牌">

                            {getBrand(assetBrandList)}
                          </Select>
                        )}
                      </FormItem>
                    </Col>

                    <Col span={6}>
                      <FormItem
                        label="设备名称"
                        hasFeedback
                      >
                        {
                          getFieldDecorator('assetName')(<Input placeholder="请输入设备名称" style={{ width: '160px' }} />)
                        }
                      </FormItem>
                    </Col>

                    <Col span={5}>
                      <div style={{ paddingLeft: '30px', paddingRight: '20px' }}>
                        <Button size="large" style={{ marginRight: '10px' }} onClick={searchHandle} type="primary" className='ant-search-btn'>搜索</Button>
                        <Button size="large" htmlType="reset" onClick={this.handleClearForm}>清空</Button>
                      </div>
                    </Col>
                  </Row>

                </Form>
              </div>
              <div style={{}}>
                <div style={{ width: '100%', padding: "20px 20px 20px" }}>
                  <Table columns={columns}
                    rowSelection={rowSelection}
                    rowKey={record => record.id_}
                    dataSource={assetList}
                    pagination={paginationDetail}
                    scroll={{ x: 1500 }}
                  />
                </div>
              </div>
            </div>
          </div>
        </Modal>
      </span>
    );
  }
}

export default Form.create()(SecondResourceGroupModal);